class SyncManager {
    constructor(authManager, taskManager, app) {  // 添加 app 参数
        this.authManager = authManager;
        this.taskManager = taskManager;
        this.app = app;  // 保存 app 引用
        // this.apiBaseUrl = 'http://yiye.localhost/api/v1';
        this.apiBaseUrl = 'https://www.ynaa.net/api/v1';
        this.syncInterval = null;
        this.autoSyncEnabled = true;
        this.autoSyncIntervalMinutes = 5;
        this.lastSyncTime = null;
        this.isSyncing = false;

        this.init();
    }

    init() {
        // 从本地存储恢复同步设置
        const savedSettings = localStorage.getItem('syncSettings');
        if (savedSettings) {
            const settings = JSON.parse(savedSettings);
            this.autoSyncEnabled = settings.autoSyncEnabled ?? true;
            this.autoSyncIntervalMinutes = settings.autoSyncIntervalMinutes ?? 5;
        }

        // 从本地存储恢复最后同步时间
        this.lastSyncTime = localStorage.getItem('lastSyncTime');

        // 启动自动同步
        this.startAutoSync();

        // 监听网络状态变化
        window.addEventListener('online', () => {
            if (this.authManager.isLoggedIn) {
                this.syncNow();
            }
        });
    }

    // 立即同步
    async syncNow() {
        try {
            console.log('开始同步任务...');

            // 先处理删除的任务
            const deleteResult = await this.handleDeletedTasks();
            if (!deleteResult.success) {
                console.warn('删除任务处理失败:', deleteResult.message);
                // 删除失败不阻止同步继续
            }

            // 上传本地任务
            const uploadResult = await this.uploadTasks();
            if (!uploadResult.success) {
                throw new Error(uploadResult.message);
            }

            // 下载服务器任务
            const downloadResult = await this.downloadTasks();
            if (!downloadResult.success) {
                throw new Error(downloadResult.message);
            }

            // 合并任务
            await this.mergeTasks(downloadResult.data);

            // 更新最后同步时间
            this.lastSyncTime = new Date().toISOString();
            localStorage.setItem('lastSyncTime', this.lastSyncTime);

            // 更新UI - 修复错误
            if (this.app && this.app.uiRenderer) {
                this.app.uiRenderer.updateUI();
            }

            console.log('任务同步完成');
            return { success: true };  // 添加返回值
        } catch (error) {
            console.error('同步失败:', error);
            // 同步失败时不清除删除记录，保留下次同步
            return { success: false, message: error.message };  // 添加返回值
        }
    }

    // 处理删除的任务
    async handleDeletedTasks() {
        try {
            const deletedTasks = JSON.parse(localStorage.getItem('deletedTasks') || '[]');

            if (deletedTasks.length === 0) {
                return { success: true };
            }

            console.log('处理删除的任务:', deletedTasks.length, '个');

            const token = localStorage.getItem('authToken');
            const tokenType = localStorage.getItem('tokenType') || 'Bearer';

            // 批量删除任务
            const response = await fetch(`${this.apiBaseUrl}/tasks/batchDelete`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': `${tokenType} ${token}`
                },
                body: JSON.stringify({
                    task_ids: deletedTasks.map(task => task.id)
                })
            });

            if (response.status === 401) {
                this.authManager.handle401Error();
                return { success: false, message: '认证失败，请重新登录' };
            }

            const data = await response.json();

            if (response.ok) {
                // 删除成功，清除本地删除记录
                localStorage.removeItem('deletedTasks');
                console.log('删除任务处理完成，已清除本地删除记录');
                return { success: true, data };
            } else {
                console.error('删除任务失败:', data);
                return { success: false, message: data.message || '删除任务失败' };
            }
        } catch (error) {
            console.error('处理删除任务时出错:', error);
            return { success: false, message: error.message };
        }
    }

    // 修改 uploadTasks 方法添加 401 处理
    async uploadTasks() {
        try {
            const token = localStorage.getItem('authToken');
            const tokenType = localStorage.getItem('tokenType') || 'Bearer';
    
            // 转换本地数据格式为后端格式
            const tasksForSync = this.taskManager.todos.map(task => ({
                id: String(task.id),
                text: task.text,
                completed: Boolean(task.completed),
                priority: task.priority || 'medium',
                dueDate: task.dueDate,
                pomodoros: task.pomodoros || 0,
                estimatedTime: task.estimatedTime || 0,
                createdAt: task.createdAt,
                updatedAt: task.updatedAt || new Date().toISOString(),
                status: task.completed ? 'completed' : (task.status || 'todo')
            }));
    
            console.log('上传任务数量:', tasksForSync.length);
            console.log('上传任务详情:', tasksForSync); // 添加详细日志
    
            // 如果没有任务，直接返回成功
            if (tasksForSync.length === 0) {
                console.log('没有任务需要上传');
                return { success: true, data: { sync_results: [], sync_time: new Date().toISOString() } };
            }
    
            const requestBody = {
                tasks: tasksForSync,
                last_sync_time: this.lastSyncTime
            };
    
            console.log('发送的请求体:', JSON.stringify(requestBody, null, 2)); // 添加请求体日志
    
            const response = await fetch(`${this.apiBaseUrl}/tasks/sync`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Authorization': `${tokenType} ${token}`
                },
                body: JSON.stringify(requestBody)
            });
    
            // 添加 401 错误处理
            if (response.status === 401) {
                this.authManager.handle401Error();
                return { success: false, message: '认证失败，请重新登录' };
            }
    
            const data = await response.json();
    
            if (!response.ok) {
                console.error('上传失败:', data);
            }
    
            return { success: response.ok, data: data.data };
        } catch (error) {
            console.error('上传任务失败:', error);
            return { success: false, message: error.message };
        }
    }

    // 修改 downloadTasks 方法添加 401 处理
    async downloadTasks() {
        try {
            const token = localStorage.getItem('authToken');
            const tokenType = localStorage.getItem('tokenType') || 'Bearer';

            const url = new URL(`${this.apiBaseUrl}/tasks`);
            if (this.lastSyncTime) {
                url.searchParams.append('since', this.lastSyncTime);
            }

            const response = await fetch(url, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': `${tokenType} ${token}`
                }
            });

            // 添加 401 错误处理
            if (response.status === 401) {
                this.authManager.handle401Error();
                throw new Error('认证失败，请重新登录');
            }

            const data = await response.json();

            if (!response.ok) {
                throw new Error(data.message || '下载任务失败');
            }

            return { success: true, data: data.data };
        } catch (error) {
            console.error('下载任务失败:', error);
            return { success: false, message: error.message };
        }
    }

    // 合并任务数据
    async mergeTasks(serverTasks) {
        console.log('开始合并任务，服务器任务:', serverTasks);

        const localTasks = this.taskManager.todos;
        const mergedTasks = new Map();

        // 获取本地删除的任务列表
        const localDeletedTasks = JSON.parse(localStorage.getItem('deletedTasks') || '[]');
        const localDeletedTaskIds = new Set(localDeletedTasks.map(t => String(t.id)));

        console.log('本地删除的任务ID:', Array.from(localDeletedTaskIds));

        // 获取服务器删除的任务列表
        const serverDeletedTasks = serverTasks.deleted_tasks || [];
        const serverDeletedTaskIds = new Set(serverDeletedTasks.map(t => String(t.id)));

        // 合并所有删除的任务ID
        const allDeletedTaskIds = new Set([...localDeletedTaskIds, ...serverDeletedTaskIds]);

        console.log('所有删除的任务ID:', Array.from(allDeletedTaskIds));

        // 添加本地任务（排除已删除的）
        localTasks.forEach(task => {
            const taskId = String(task.id);
            if (!allDeletedTaskIds.has(taskId)) {
                mergedTasks.set(taskId, { ...task, id: taskId, source: 'local' });
            } else {
                console.log('排除本地已删除任务:', taskId);
            }
        });

        // 合并服务器任务（排除软删除的和本地已删除的）
        const activeTasks = (serverTasks.tasks || serverTasks).filter(task => {
            const isDeleted = task.status === 'deleted' || task.deleted_at;
            const isLocalDeleted = localDeletedTaskIds.has(String(task.id));

            if (isDeleted) {
                console.log('排除服务器软删除任务:', task.id);
            }
            if (isLocalDeleted) {
                console.log('排除本地已删除任务:', task.id);
            }

            return !isDeleted && !isLocalDeleted;
        });

        console.log('服务器活跃任务数量:', activeTasks.length);

        activeTasks.forEach(serverTask => {
            const serverId = String(serverTask.id);
            const localTask = mergedTasks.get(serverId);

            if (!localTask) {
                mergedTasks.set(serverId, { ...serverTask, id: serverId, source: 'server' });
            } else {
                // 比较更新时间，选择最新版本
                const serverUpdatedAt = new Date(serverTask.updated_at || serverTask.updatedAt);
                const localUpdatedAt = new Date(localTask.updatedAt || localTask.updated_at);

                if (serverUpdatedAt > localUpdatedAt) {
                    mergedTasks.set(serverId, { ...serverTask, id: serverId, source: 'server' });
                }
            }
        });

        console.log('合并后任务数量:', mergedTasks.size);

        // 更新任务列表
        this.taskManager.todos = Array.from(mergedTasks.values()).map(task => ({
            id: String(task.id),
            text: task.text || task.title,
            description: task.description || '',
            completed: Boolean(task.completed || task.status === 'completed'),
            priority: task.priority || 'medium',
            dueDate: task.dueDate || task.due_date,
            pomodoros: task.pomodoros || task.estimated_pomodoros || 0,
            estimatedTime: task.estimatedTime || task.estimated_time || 0,
            createdAt: task.createdAt || task.created_at,
            updatedAt: task.updatedAt || task.updated_at || new Date().toISOString(),
            completedAt: task.completedAt || task.completed_at,
            status: task.completed || task.status === 'completed' ? 'completed' : (task.status || 'todo'),
            category: (task.metadata && task.metadata.category) || task.category || 'today'
        }));

        await this.taskManager.saveTodos();
        console.log('任务合并完成，最终任务数量:', this.taskManager.todos.length);
    }

    // 启动自动同步
    startAutoSync() {
        this.stopAutoSync(); // 先停止现有的定时器

        if (this.autoSyncEnabled && this.authManager.isLoggedIn) {
            const intervalMs = this.autoSyncIntervalMinutes * 60 * 1000;
            this.syncInterval = setInterval(() => {
                if (navigator.onLine && this.authManager.isLoggedIn) {
                    this.syncNow();
                }
            }, intervalMs);

            console.log(`自动同步已启动，间隔：${this.autoSyncIntervalMinutes}分钟`);
        }
    }

    // 停止自动同步
    stopAutoSync() {
        if (this.syncInterval) {
            clearInterval(this.syncInterval);
            this.syncInterval = null;
            console.log('自动同步已停止');
        }
    }

    // 更新同步设置
    updateSyncSettings(settings) {
        this.autoSyncEnabled = settings.autoSyncEnabled ?? this.autoSyncEnabled;
        this.autoSyncIntervalMinutes = settings.autoSyncIntervalMinutes ?? this.autoSyncIntervalMinutes;

        // 保存设置
        localStorage.setItem('syncSettings', JSON.stringify({
            autoSyncEnabled: this.autoSyncEnabled,
            autoSyncIntervalMinutes: this.autoSyncIntervalMinutes
        }));

        // 重启自动同步
        this.startAutoSync();
    }

    // 更新同步UI状态
    updateSyncUI(status) {
        const syncItem = document.querySelector('[data-action="sync"] span');
        const syncNowItem = document.querySelector('[data-action="sync-now"] span');

        switch (status) {
            case 'syncing':
                if (syncItem) syncItem.textContent = '同步中...';
                if (syncNowItem) syncNowItem.textContent = '同步中...';
                break;
            case 'success':
                const timeStr = this.formatSyncTime(this.lastSyncTime);
                if (syncItem) syncItem.textContent = `最后同步：${timeStr}`;
                if (syncNowItem) syncNowItem.textContent = '立即同步';
                break;
            case 'error':
                if (syncItem) syncItem.textContent = '同步失败';
                if (syncNowItem) syncNowItem.textContent = '重试同步';
                break;
        }
    }

    // 格式化同步时间
    formatSyncTime(timeStr) {
        if (!timeStr) return '从未';

        const syncTime = new Date(timeStr);
        const now = new Date();
        const diffMs = now - syncTime;
        const diffMinutes = Math.floor(diffMs / (1000 * 60));

        if (diffMinutes < 1) return '刚刚';
        if (diffMinutes < 60) return `${diffMinutes}分钟前`;

        const diffHours = Math.floor(diffMinutes / 60);
        if (diffHours < 24) return `${diffHours}小时前`;

        const diffDays = Math.floor(diffHours / 24);
        return `${diffDays}天前`;
    }

    // 获取同步状态
    getSyncStatus() {
        return {
            isLoggedIn: this.authManager.isLoggedIn,
            isSyncing: this.isSyncing,
            lastSyncTime: this.lastSyncTime,
            autoSyncEnabled: this.autoSyncEnabled,
            autoSyncIntervalMinutes: this.autoSyncIntervalMinutes,
            isOnline: navigator.onLine
        };
    }
}

module.exports = SyncManager;